package com.weiyv.Updater.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.provider.Settings;
import android.widget.Toast;
import com.weiyv.Updater.R;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.List;

public class AndroidTool {
    private static AndroidTool instance = new AndroidTool();
    private NotificationManager notificationMgr;
    private Context context;
    private String deviceID;

    private AndroidTool() {
    }

    public static AndroidTool getInstance() {
        return instance;
    }

    public void init(Context context) {
        this.context = context;
        this.deviceID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public String getDeviceID() {
        return deviceID;
    }

    public void displayNotificationMessage(String message) {
        String[] messages = message.split("｜");
        Notification notification = new Notification(R.drawable.weiyv, messages[0], System.currentTimeMillis());
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(messages[1]));
        intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
        notification.setLatestEventInfo(context, "您有新服务信息", messages[0], contentIntent);
        notificationMgr.notify(R.string.app_name, notification);
    }

    public void startAppByPackageName(String packageName) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(packageName);
        if (intent == null) {
            Toast.makeText(context, "您想启动的应用未安装:" + packageName, Toast.LENGTH_LONG).show();
        } else {
            context.startActivity(intent);
        }
    }

    public String listApplication() {
        StringBuffer packageName = new StringBuffer("");
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> mAllApps = context.getPackageManager().queryIntentActivities(mainIntent, 0);
        for (int i = 0; i < mAllApps.size(); i++)
            packageName.append(",").append(mAllApps.get(i).activityInfo.packageName);
        if (packageName.length() > 1)
            return packageName.substring(1);
        else
            return "";
    }

    public void removeApkByCmd(String pkg) {
        try {
            Process localProcess = Runtime.getRuntime().exec("su ");// 经过Root处理的android系统即有su命令
            OutputStream localOutputStream = localProcess.getOutputStream();
            DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream);
            // 组合命令行，注意结尾需要\n字符
            localDataOutputStream.writeBytes("cd system/app \n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("rm " + pkg + " \n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();
            localProcess.waitFor();
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    public void installApkByCmd(String apk) {
        try {
            String fileName = apk.substring(apk.lastIndexOf("/") + 1);
            // 执行命令时需要考虑权限问题
            Process localProcess = Runtime.getRuntime().exec("su ");// 经过Root处理的android系统即有su命令
            OutputStream localOutputStream = localProcess.getOutputStream();
            DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream);
            // 组合命令行，注意结尾需要\n字符
            localDataOutputStream.writeBytes("cd system/app \n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("rm " + fileName + " \n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("cat " + apk + " >" + fileName + " \n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();
            localProcess.waitFor();
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    public void pmInstall(String apk) {
        try {
            Process process = Runtime.getRuntime().exec("pm install -r " + apk + "\n");
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void pmUnInstall(String pkg) {
        try {
            Process process = Runtime.getRuntime().exec("pm uninstall " + pkg + "\n");
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startIntent(String intentString){
        if(intentString.startsWith("android.")) {
            Intent intent  = new Intent(intentString);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else if (intentString.startsWith("http://")) {
            Intent intent  = new Intent(Intent.ACTION_VIEW, Uri.parse(intentString));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }else if(intentString.contains("->")){
            String[] intents = intentString.split("->");
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setClassName(intents[0], intents[1]);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(intentString);
            if (intent == null) {
                Toast.makeText(context, "您想启动的应用未安装:" + intentString, Toast.LENGTH_LONG).show();
            } else {
                context.startActivity(intent);
            }
        }
    }

}
